package hhtc.jsjds.utils;

import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.core.io.Resource;
import org.springframework.core.io.UrlResource;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.net.MalformedURLException;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.nio.file.StandardCopyOption;
import java.util.Map;
import java.util.Objects;

/**
 * @author czh
 */
@Slf4j
public class OssUtils {
    public static String address ="http://10.22.105.20:10010/upload-service/upload/fetch/" ;
    public static Path ROOT_URL= Paths.get("storage");

    /**
     * @param file             上传文件
     * @param bucketName       bucketName 桶名称 如：hhtc，zhangyioss,自定义创建的Bucket 名称
     * @param objectFileOssUrl Bucket中的存储路径，建议只写文件夹路径，具体文件自己定义 如：student/
     * @return 是否上传成功
     */
    public static Map<String, Object> upload(MultipartFile file, String bucketName, String objectFileOssUrl) {
        String url = null;
        try {
            //1. 生成时间戳当做文件名
            String s = System.currentTimeMillis()+file.getOriginalFilename();
            //上传图片至阿里云OSS
            if (file != null && StringUtils.isNotBlank(bucketName) && StringUtils.isNotBlank(objectFileOssUrl)) {
                Path path = ROOT_URL.resolve(s);
                log.info("path={}",path);
                try {
                    Files.createDirectories(ROOT_URL);
                    Files.copy(file.getInputStream(),path, StandardCopyOption.REPLACE_EXISTING);
                } catch (IOException e) {
                    throw new RuntimeException("Failed to store file " + file.getOriginalFilename(), e);
                }
                //拼接图片访问路径并返回
                url = address +"/"+ s;
                return new MapUtils().put("result", true).put("url", url);
            }
            return new MapUtils().put("result", false).put("url", url);
        } catch (Exception e) {
            e.printStackTrace();
            return new MapUtils().put("result", false).put("url", url);
        }

    }

    public static Resource loadAsResource(String filename) {
        try {
            Path file = ROOT_URL.resolve(filename);
            Resource resource = new UrlResource(file.toUri());
            if (resource.exists() || resource.isReadable()) {
                return resource;
            } else {
                return null;
            }
        } catch (MalformedURLException e) {
            e.printStackTrace();
            return null;
        }
    }
}
